package com.dabaozhan.modules.wx_app.facade.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dabaozhan.common.exception.RRException;
import com.dabaozhan.common.utils.DateUtils;
import com.dabaozhan.modules.wx_app.base.PageResult;
import com.dabaozhan.modules.wx_app.dao.SiteCategoryMapper;
import com.dabaozhan.modules.wx_app.entity.FormQueryEntity;
import com.dabaozhan.modules.wx_app.entity.HistogramRequestEntity;
import com.dabaozhan.modules.wx_app.entity.HistogramResponseEntity;
import com.dabaozhan.modules.wx_app.entity.FormPersonResponseEntity;
import com.dabaozhan.modules.wx_app.entity.SaleFormEntity;
import com.dabaozhan.modules.wx_app.entity.SiteCategoryEntity;
import com.dabaozhan.modules.wx_app.enums.ResponseCodeEnum;
import com.dabaozhan.modules.wx_app.facade.SaleFormFacade;
import com.dabaozhan.modules.wx_app.service.SaleFormService;

@Service("saleFormFacade")
public class SaleFormFacadeImpl implements SaleFormFacade{

	@Autowired
	private SaleFormService saleFormService;
	@Autowired
	private SiteCategoryMapper siteCategoryMapper;
	
	@Override
	public PageResult<List<FormPersonResponseEntity>> getSaleList(FormQueryEntity entity) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int tomeSection = entity.getTimeSection();
		Date beginDate = DateUtils.getBeginDate(tomeSection);
		Date endDate = DateUtils.getEndDate(tomeSection);
		entity.setBeginTime(format.format(beginDate));
		entity.setEndTime(format.format(endDate));
		List<SaleFormEntity> list = saleFormService.getSaleList(entity);
		if(CollectionUtils.isEmpty(list)){
			throw new RRException(ResponseCodeEnum.ResponseCode_400.getCode(),ResponseCodeEnum.ResponseCode_400.getDescription());
		}
		List<FormPersonResponseEntity> resultList = new ArrayList<FormPersonResponseEntity>();
		for(SaleFormEntity sale:list){
			String name = sale.getName();
			if(StringUtils.isBlank(name)){
				continue;
			}
			//resultList 中没有这个厂
			if(!judgeSaleExist(resultList,name)){
				List<SaleFormEntity> limitList = list.stream().filter(l->name.equals(l.getName())).collect(Collectors.toList());
				BigDecimal totalPrice =  limitList.stream().map(SaleFormEntity::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
				BigDecimal totalWeight =  limitList.stream().map(SaleFormEntity::getTotalWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
				BigDecimal averagePrice = null;
				if(totalWeight.compareTo(BigDecimal.ZERO) !=0){
					averagePrice = totalPrice.divide(totalWeight, 2,BigDecimal.ROUND_DOWN);
				}
				int times = limitList.size();
				FormPersonResponseEntity pEntity = new FormPersonResponseEntity();
				pEntity.setName(name);
				pEntity.setTotalPrice(totalPrice);
				pEntity.setTotalWeight(totalWeight);
				pEntity.setAveragePrice(averagePrice);
				pEntity.setTimes(times);
				resultList.add(pEntity);
			}
		}
		//查询开始区间
		int beginIndex = (entity.getPage()-1)*entity.getSize();
		//查询结束区间
		int endIndex = entity.getPage()*entity.getSize();
		//按照重量排序从大到小排序
		Comparator<FormPersonResponseEntity> comparator = (h1, h2) -> h1.getTotalWeight().compareTo(h2.getTotalWeight());
		resultList.sort(comparator.reversed());
		Integer totalCount = resultList.size();
		PageResult<List<FormPersonResponseEntity>> pageResult = new PageResult<List<FormPersonResponseEntity>>();
		pageResult.setTotal(totalCount);
		
		//分页限制判断 理论上不会进入此逻辑
		if(beginIndex>totalCount-1){
			pageResult.setListData(null);
		}else{
			List<FormPersonResponseEntity> responseList= resultList.subList(beginIndex, endIndex > totalCount?totalCount:endIndex);
			pageResult.setListData(responseList);
		}
		return pageResult;
	}
	
	//判断 是否存在  存在返回 true  不存在返回false
	private static boolean judgeSaleExist(List<FormPersonResponseEntity> l,String name){
		boolean r = false;
		for(FormPersonResponseEntity entity:l){
			if(name.equals(entity.getName())){
				return true;
			}
		}
		return r;
	}
	
	@Override
	public List<HistogramResponseEntity> getSaleHistogram(HistogramRequestEntity entity) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int tomeSection = entity.getTimeSection();
		Date beginDate = DateUtils.getBeginDate(tomeSection);
		Date endDate = DateUtils.getEndDate(tomeSection);
		entity.setBeginTime(format.format(beginDate));
		entity.setEndTime(format.format(endDate));
		FormQueryEntity formQuery = new FormQueryEntity();
		formQuery.setUserId(entity.getUserId());
		formQuery.setBeginTime(entity.getBeginTime());
		formQuery.setEndTime(entity.getEndTime());
		List<SaleFormEntity> list = saleFormService.getSaleList(formQuery);
		if(CollectionUtils.isEmpty(list)){
			throw new RRException(ResponseCodeEnum.ResponseCode_400.getCode(),ResponseCodeEnum.ResponseCode_400.getDescription());
		}
		List<SiteCategoryEntity> categoryList = siteCategoryMapper.getCategoryListByUserId(entity.getUserId());
		List<HistogramResponseEntity> resultList = new ArrayList<HistogramResponseEntity>();
		for(SaleFormEntity pfe:list){
			String categoryId = pfe.getCategoryId();
			String parentId = pfe.getParentId();
			if(StringUtils.isBlank(categoryId) || StringUtils.isBlank(categoryId)){
				continue;
			}
			if(!PurchaseFormFacadeImpl.judgeCategoryIdExist(resultList,parentId,categoryId)){
				List<SaleFormEntity> limitList = list.stream().filter(l->categoryId.equals(l.getCategoryId())).collect(Collectors.toList());
				BigDecimal totalWeight =  limitList.stream().map(SaleFormEntity::getTotalWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
				HistogramResponseEntity responseEntity = new HistogramResponseEntity();
				responseEntity.setParentId(pfe.getParentId());
				responseEntity.setCategoryId(categoryId);
				responseEntity.setCategoryName(PurchaseFormFacadeImpl.getCategoryName(categoryList,parentId,categoryId));
				responseEntity.setTotalWeight(totalWeight);
				resultList.add(responseEntity);
			}
		}
		if(CollectionUtils.isEmpty(resultList)){
			throw new RRException(ResponseCodeEnum.ResponseCode_400.getCode(),ResponseCodeEnum.ResponseCode_400.getDescription());
		}
		//按照重量排序从大到小排序
		resultList.sort((h1, h2) -> h2.getTotalWeight().compareTo(h1.getTotalWeight()));
		return resultList;
	}
	
}
